﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;

namespace FAST
{
    //UI CLASS
    public partial class MainUI : Form
    {
        //UI Global Variables
        private Main ctrl; 
        private int indexSelected;
        private bool isBalanceView;

        private List<FilesHandler> leftTreeDetails;
        private List<FilesHandler> rightTreeDetails;

        private const int FILE_NOT_EXIST = 7; // copy file over
        private const int FILE_MODIFIED = 8;
        private const int FILE_IDENTICAL = 9;

        private SessionUI sessionUI; 

        //MainUI Constructor
        public MainUI()
        {
            try
            {
                ctrl = new Main();
                InitializeComponent();

                this.FormClosed += new FormClosedEventHandler(this.syncTool_OnClose);
                this.fileDetailsLeftMenu.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.fileDetailsLeftMenu_ItemClicked);
                this.fileDetailsRightMenu.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.fileDetailsRightMenu_ItemClicked);
                this.folderDetailsLeftMenu.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.folderDetailsLeftMenu_ItemClicked);
                this.folderDetailsRightMenu.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.folderDetailsRightMenu_ItemClicked);

                hoverPanel.MouseHover += new EventHandler(this.hoverPanel_MouseHover);
                this.MouseHover += new EventHandler(this.form_MouseHover);
                fileViewLeft.MouseHover += new EventHandler(this.form_MouseHover);
                fileViewRight.MouseHover += new EventHandler(this.form_MouseHover);
                tabControl1.MouseHover += new EventHandler(this.form_MouseHover);

                ToolTip tt = new ToolTip();
                tt.SetToolTip(btnPreview, "Preview");
                tt.SetToolTip(btnSync, "Sync");
                tt.SetToolTip(folderCompare, "Folder Compare");

                refreshSyncTool();
                if (ctrl.getLoadedSessionIndex() < 0) 
                {
                    clearSessionToolStripMenuItem.Enabled = false;
                }
              }
            catch (Exception ex) //catch any uncaught exceptions
            {
                Console.WriteLine(ex.ToString());
            }
        }

        //use to remove and show border
        public void form_MouseHover(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.None;
        }

        public void hoverPanel_MouseHover(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.Sizable;
        }

        //MainUI form close event
        //internal use
        private void syncTool_OnClose(object sender, EventArgs e)
        {
            if (ctrl.getLoadedSessionIndex() >= 0)
            {
                DialogResult dMsg = MessageBox.Show("Save current session?", "FAST", MessageBoxButtons.YesNo,MessageBoxIcon.Question);
                if (dMsg == DialogResult.No)
                {
                    ctrl.clearCurrentSession();
                }
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ctrl.getLoadedSessionIndex() >= 0)
            {
                DialogResult dMsg = MessageBox.Show("Save current session?", "FAST", MessageBoxButtons.YesNo,MessageBoxIcon.Question);
                if (dMsg == DialogResult.No)
                {
                    ctrl.clearCurrentSession();
                }
            }
            this.Dispose();
        }

        //refresh the sync tool except listview preview
        //generate session menu load items at the same time
        private void refreshSyncTool()
        {
            sessionLog.Text = ctrl.getSessionLog();
            isBalanceView = false;
            txtLFolder.Text = ctrl.getSessionLeftFolderPath();
            txtRFolder.Text = ctrl.getSessionRightFolderPath();

            if (ctrl.isSessionsEmpty())
            {
                sessionUI = new SessionUI(this);
                clearSessionToolStripMenuItem.Enabled = false;

                syncSessionToolStripMenuItem.DropDown.Items.Clear();
                syncSessionToolStripMenuItem.DropDown.Items.Add("Empty");
                syncSessionToolStripMenuItem.DropDown.Items[0].Enabled = false;

                otherSessionToolStripMenuItem.DropDown.Items.Clear();
                otherSessionToolStripMenuItem.DropDown.Items.Add("Empty");
                otherSessionToolStripMenuItem.DropDown.Items[0].Enabled = false;
            }
            else
            {
                clearSessionToolStripMenuItem.Enabled = true;

                sessionUI = new SessionUI(this);

                List<SessionItem> items = ctrl.retrieveSessions();
                
                syncSessionToolStripMenuItem.DropDown.Items.Clear();
                otherSessionToolStripMenuItem.DropDown.Items.Clear();

                ToolStripMenuItem tsItem;

                int index = 0;
                foreach (SessionItem item in items)
                {
                    string creationTime = "";
                    if (ctrl.getLoadedSessionIndex() == index)
                        creationTime = "Created at: " + item.getCreatedTimeStamp().ToString() + " [Loaded]";
                    else
                        creationTime = "Created at: " + item.getCreatedTimeStamp().ToString();

                    ListViewItem listViewItem = new ListViewItem(index+"");
                    listViewItem.SubItems.Add(item.getCreatedTimeStamp().ToString());
                    listViewItem.SubItems.Add(item.getUpdatedTimeStamp().ToString());
                    
                    tsItem = new ToolStripMenuItem(creationTime);
                    tsItem.Name = "" + index;
                    
                    string osExistField = "";
                    if (item.isOSExist())//check sync before
                    {
						osExistField = "Yes";
                        tsItem.ToolTipText = "Left Folder: " + item.getLeftFolderPath() + "\nRight Folder: " + item.getRightFolderPath() + "\n" + "Last Updated: " + item.getUpdatedTimeStamp();//fill number of syncs after versioning complete
                        syncSessionToolStripMenuItem.DropDown.Items.Add(tsItem);
                    }
                    else
                    {
						osExistField = "No";
                        tsItem.ToolTipText = "Last Updated: " + item.getUpdatedTimeStamp();//fill number of syncs after versioning complete
                        otherSessionToolStripMenuItem.DropDown.Items.Add(tsItem);
                    }

                    listViewItem.SubItems.Add(osExistField);
                    sessionUI.addListViewItem(listViewItem);

                    index++;
                }

                if (syncSessionToolStripMenuItem.DropDown.Items.Count == 0)
                {
                    syncSessionToolStripMenuItem.DropDown.Items.Clear();
                    syncSessionToolStripMenuItem.DropDown.Items.Add("Empty");
                    syncSessionToolStripMenuItem.DropDown.Items[0].Enabled = false;
                }
                else if (otherSessionToolStripMenuItem.DropDown.Items.Count == 0)
                {
                    otherSessionToolStripMenuItem.DropDown.Items.Clear();
                    otherSessionToolStripMenuItem.DropDown.Items.Add("Empty");
                    otherSessionToolStripMenuItem.DropDown.Items[0].Enabled = false;
                }

                syncSessionToolStripMenuItem.DropDownItemClicked += new ToolStripItemClickedEventHandler(this.loadSessionToolStripMenuItem_DropDown_ItemClicked);
                otherSessionToolStripMenuItem.DropDownItemClicked += new ToolStripItemClickedEventHandler(this.loadSessionToolStripMenuItem_DropDown_ItemClicked);
            }
        }

        //Clear data in ListView Preview
        private void resetPreview()
        {
            txtLFolder.Text = "";
            txtRFolder.Text = "";
            fileViewLeft.Items.Clear();
            fileViewRight.Items.Clear();
        }

        //Event on click browse left
        private void btnBrowseL_Click(object sender, EventArgs e)
        {
            String lBrowseFolder;

            if (BrowseFolderDialog.ShowDialog() == DialogResult.OK)
            {
                lBrowseFolder = BrowseFolderDialog.SelectedPath;
                txtLFolder.Text = lBrowseFolder;
                txtLFolder.Text = lBrowseFolder;
                txtLFolder.Items.Add(lBrowseFolder);
            }
        }

        //Event on click browse right
        private void btnBrowseR_Click(object sender, EventArgs e)
        {
            String rBrowseFolder;

            if (BrowseFolderDialog.ShowDialog() == DialogResult.OK)
            {
                rBrowseFolder = BrowseFolderDialog.SelectedPath;
                txtRFolder.Text = rBrowseFolder;
                txtRFolder.Items.Add(rBrowseFolder);
            }
        }

        /********************************************** Session UI methods **********************************************************/

        private void clearSessionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ctrl.clearCurrentSession();
            MessageBox.Show("This session has been successfully cleared.", "FAST", MessageBoxButtons.OK,MessageBoxIcon.Information);

            refreshSyncTool();
            resetPreview();
            clearAll_log();
            this.Enabled = false;
            sessionUI.Show();
        }


        private void newSessionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ctrl.createNewSession();
            refreshSyncTool();
            resetPreview();
            clearAll_log();
        }

        //SessionUI form able to access this method too
        public void clickNewSessionToolStripMenuItem()
        {
            ctrl.createNewSession();
            refreshSyncTool();
            resetPreview();
            clearAll_log();
            MessageBox.Show("A new session has been successfully created.","FAST",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }

        private void loadSessionToolStripMenuItem_DropDown_ItemClicked(object sender, EventArgs e)
        {
            ToolStripItemCollection items = syncSessionToolStripMenuItem.DropDown.Items;
            ToolStripItemCollection items2 = otherSessionToolStripMenuItem.DropDown.Items;

            DialogResult dMsg;
            int idxToLoad = items.Count - 1;
            foreach (ToolStripMenuItem item in items) 
            {
                if (item.Selected)
                {
                    dMsg = MessageBox.Show("Are you sure you want to load this session?", "FAST", MessageBoxButtons.YesNo,MessageBoxIcon.Question);//No selection yet -> default is Yes
                    if (dMsg == DialogResult.Yes)
                    {
                        idxToLoad = int.Parse(item.Name);
                        ctrl.loadSessionByIdx(idxToLoad);
                        refreshSyncTool();
                        break;
                    }
                  
                }
            }

            foreach (ToolStripMenuItem item2 in items2)
            {
                if (item2.Selected)
                {
                    dMsg = MessageBox.Show("Are you sure you want to load this session?", "FAST", MessageBoxButtons.YesNo,MessageBoxIcon.Question);//No selection yet -> default is Yes
                    if (dMsg == DialogResult.Yes)
                    {
                        idxToLoad = int.Parse(item2.Name);
                        ctrl.loadSessionByIdx(idxToLoad);
                        refreshSyncTool();
                        resetPreview();
                        break;
                    }
                }
            }

        }

        /********************************************** End Session UI methods ******************************************************/
        
        
        //For SessionUI form use 
        public void loadSessionByIndex(int idx)
        {
            ctrl.loadSessionByIdx(idx);
            refreshSyncTool();
            previewAction(txtLFolder.Text, txtRFolder.Text);
        }

        
        /****************************************** ListView UI Methods ************************************************************/

        //Process a folder ListViewItem
        //No showing of folder differences
        //Only generates folder meta data
        private ListViewItem processFolderListViewItem(FolderHandler folder, int index)
        {
            string dirName = folder.getSubFolderPath().Substring(1);

            string[] tokens = dirName.Split('\\');
            int size = tokens.Length;
            ListViewItem item = new ListViewItem(tokens[size - 1]);
            item.IndentCount = size;
            item.ToolTipText = "Folder";
            
            item.ImageIndex = 1;//display folder image
            item.Name = "" + index; 
            item.SubItems.Add("Directory");
            item.SubItems.Add("");
            item.SubItems.Add(folder.getDi().LastWriteTime + "");

            return item;
        }

        //Process file ListViewItem
        //Show file differences
        //Show file meta data
        private ListViewItem processFileListViewItem(FileHandler file, int index, bool isFolderCompare)
        {
            string fileName = file.getSubFilePath().Substring(1);

            string[] tokens = fileName.Split('\\');
            int size = tokens.Length;

            ListViewItem item = new ListViewItem(" " + tokens[size - 1]);
            item.IndentCount = size;
            
            item.ImageIndex = 0;
            item.Name = ""+index;

            item.SubItems.Add("File");
            item.SubItems.Add(file.getFileLength() + "b");
            item.SubItems.Add(file.getLastModTime() + "");

            item.ToolTipText = file.getFi().Name;
            //int vIdx = file.getIndexToVersion();
            if (!isFolderCompare)
            {
                int vIdx = file.getVersioningIdx();
                int vCount = 0;
                if (vIdx != -1)
                {
                    List<FileHandler> vList = ctrl.getFVList()[file.getVersioningIdx()].getListOfFH();
                    vCount = vList.Count; //convert to method in main
                    item.SubItems.Add(vCount + "");
                    int vNum = 0;
                    foreach (FileHandler fh in vList)
                    {
                        item.ToolTipText += "\nv" + vNum + " Comments:\n";
                        item.ToolTipText += "" + fh.getComments() + "\n";
                        vNum++;
                    }
                }
                else
                {
                    item.SubItems.Add(0 + "");
                    item.ToolTipText += "\nNo Versions Exist";
                }
            }
            
            int fileStatus = file.getFileStatus();
            switch (fileStatus)
            {
                case FILE_NOT_EXIST:
                    item.ForeColor = Color.Red;
                    break;
                case FILE_MODIFIED:
                    item.ForeColor = Color.Blue;
                    break;
                case FILE_IDENTICAL:
                    item.ForeColor = Color.Green;
                    break;
            }

            return item;
        }

        //Folder Compare Left and Right ListView
        private void populateLeftRightUIListView()
        {
            isBalanceView = true;

            leftTreeDetails = ctrl.generateLeftTree();
            rightTreeDetails = ctrl.generateRightTree();

            int sizeL, sizeR;
            sizeL = leftTreeDetails.Count;
            sizeR = rightTreeDetails.Count;

            int start = 0;
            ListViewItem itemL, itemR;

            for (int i = 0; i < sizeL; i++)
            {
                if ( leftTreeDetails[i].getFileType() )//if file
                {
                    itemL = processFileListViewItem( ((FileHandler)leftTreeDetails[i]), i , true);

                    if (((FileHandler)leftTreeDetails[i]).getFileStatus() != FILE_NOT_EXIST)
                    {
                        for (int j = start; j < sizeR; j++)
                        {
                            if (rightTreeDetails[j].getFileType()) //check is file
                            {
                                itemR = processFileListViewItem( ((FileHandler)rightTreeDetails[j]), j , true);
                                if (((FileHandler)leftTreeDetails[i]).getSubFilePath().Equals(((FileHandler)rightTreeDetails[j]).getSubFilePath()))
                                {
                                    fileViewLeft.Items.Add(itemL);
                                    fileViewRight.Items.Add(itemR);
                                    start = j + 1;
                                    break;
                                }
                                else
                                {
                                    fileViewLeft.Items.Add(new ListViewItem(""));
                                    fileViewRight.Items.Add(itemR);
                                }
                            }
                            else//else if folder
                            {
                                itemR = processFolderListViewItem((FolderHandler)rightTreeDetails[j],j);
                                fileViewLeft.Items.Add(new ListViewItem(""));
                                fileViewRight.Items.Add(itemR);
                            }
                        }
                    }
                    else
                    {
                        fileViewLeft.Items.Add(itemL);
                        fileViewRight.Items.Add(new ListViewItem(""));
                    }
                }
                else //ELSE TYPE IS FOLDER
                {
                    itemL = processFolderListViewItem((FolderHandler)leftTreeDetails[i],i);
                    
                    if (((FolderHandler)leftTreeDetails[i]).getFolderStatus() != FILE_NOT_EXIST)
                    {
                        for (int j = start; j < sizeR; j++)
                        {
                            if ((rightTreeDetails[j].getFileType() == false))
                            {
                                itemR = processFolderListViewItem((FolderHandler)rightTreeDetails[j],j);
                                if (((FolderHandler)leftTreeDetails[i]).getSubFolderPath().Equals(((FolderHandler)rightTreeDetails[j]).getSubFolderPath()))
                                {
                                    fileViewLeft.Items.Add(itemL);
                                    fileViewRight.Items.Add(itemR);
                                    start = j + 1;
                                    break;
                                }
                                else
                                {
                                    fileViewLeft.Items.Add(new ListViewItem(""));
                                    fileViewRight.Items.Add(itemR);
                                }
                            }
                            else
                            {
                                itemR = processFileListViewItem((FileHandler)rightTreeDetails[j], j , true);
                                fileViewLeft.Items.Add(new ListViewItem(""));
                                fileViewRight.Items.Add(itemR);
                            }
                        }
                    }
                    else
                    {
                        fileViewLeft.Items.Add(itemL);
                        fileViewRight.Items.Add(new ListViewItem(""));
                    }
                }

            }

            if (start < sizeR)
            {
                for (int k = start; k < sizeR; k++)
                {
                    fileViewLeft.Items.Add(new ListViewItem(""));
                    if (rightTreeDetails[k].getFileType())
                        itemR = processFileListViewItem((FileHandler)rightTreeDetails[k], k, true);
                    else
                        itemR = processFolderListViewItem((FolderHandler)rightTreeDetails[k],k);
                    
                    fileViewRight.Items.Add(itemR);
                }
            }

        }

        //Generate Left ListView without Folder Compare
        public void generateUILeftTree()
        {
            leftTreeDetails = ctrl.generateLeftTree();
            ListViewItem item;
            int index = 0;
            //leftTree.Add( new ListViewItem( ((FolderHandler)leftTreeDetails[0]).getFullFolderPath() ) );
            foreach (FilesHandler fh in leftTreeDetails)
            {
                if (fh.getFileType())
                {
                    item = processFileListViewItem((FileHandler)fh, index, false);
                }
                else
                {
                    item = processFolderListViewItem((FolderHandler)fh, index);
                }

                index++;
                fileViewLeft.Items.Add(item);
            }
        }

        //Generate Right ListView without Folder Compare
        public void generateUIRightTree()
        {
            rightTreeDetails = ctrl.generateRightTree();
            
            ListViewItem item;
            int index = 0;

            foreach (FilesHandler fh in rightTreeDetails)
            {
                if (fh.getFileType())
                {
                    item = processFileListViewItem((FileHandler)fh, index, false);
                }
                else
                {
                    item = processFolderListViewItem((FolderHandler)fh, index);
                }
                index++;
                fileViewRight.Items.Add(item);
            }
            
        }

        /****************************************** End ListView UI Methods ********************************************************/

        /****************************************** Preview, Folder Compare, Sync Button UI Methods ********************************************************/
        
        //Method to use in preview without Folder Compare
        private void previewAction(string leftRootPath, string rightRootPath)
        {
            ctrl = new Main();

            isBalanceView = false;
            fileViewLeft.Items.Clear();
            fileViewRight.Items.Clear();

            ctrl.previewOnly(leftRootPath, rightRootPath);
            
            //without balancing
            generateUILeftTree();
            generateUIRightTree();                
        }

        //Method to use in folder compare
        private void folderCompareAction(string leftRootPath, string rightRootPath)
        {
            ctrl = new Main();

                fileViewLeft.Items.Clear();
                fileViewRight.Items.Clear();

            ctrl.previewWithoutOS(leftRootPath, rightRootPath);

            populateLeftRightUIListView();
        }

        //Preview Button Event
        public void btnPreview_Click(object sender, EventArgs e)
        {
            try
            {
                btnPreview.Enabled = false;
                String lRoot = txtLFolder.Text;
                String rRoot = txtRFolder.Text;
                verifyLocation(lRoot, rRoot);
                previewAction(lRoot, rRoot);
            }
            catch (CustomException ex) //catch custom exception
            {
                MessageBox.Show(ex.Message, "Folder(s) not existent/selected error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex) //catch any uncaught exceptions
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                btnPreview.Enabled = true;
            }

        }

        //Folder Compare Button Event
        private void folderCompare_Click(object sender, EventArgs e)
        {
            try
            {
                String lRoot = txtLFolder.Text;
                String rRoot = txtRFolder.Text;
                verifyLocation(lRoot, rRoot);
                folderCompare.Enabled = false;
                folderCompareAction(lRoot, rRoot);
                folderCompare.Enabled = true;
            }
            catch (CustomException ex) //catch custom exception
            {
                MessageBox.Show(ex.Message, "Folder(s) not existent/selected error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex) //catch any uncaught exceptions
            {
                Console.WriteLine(ex.ToString());
            }
        }

        //Sync Button Event
        private void btnSync_Click(object sender, EventArgs e)
        {
            try
            {
                btnSync.Enabled = false;
                ctrl = new Main();

                String lRoot = txtLFolder.Text;
                String rRoot = txtRFolder.Text;
                verifyLocation(lRoot, rRoot);

                MessageLog msgObj = ctrl.twoWaySync(lRoot, rRoot);
                previewAction(lRoot, rRoot);

                int errors = batchUILogUpdate(msgObj);

                if (errors == 0)
                {
                    MessageBox.Show("Your folders are now in sync.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("There are some error occured during synchronization process. Some of the files are now in sync, some are not.", "Success With Exception", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                refreshSyncTool();
            }
            catch (CustomException ex) //catch custom exception
            {
                MessageBox.Show(ex.Message, "Folder(s) not existent/selected error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex) //catch any uncaught exceptions
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                btnSync.Enabled = true;
            }
        }

        /****************************************** End Preview, Folder Compare, Sync Button UI Methods *****************************************************/
        

        //Method to generate Log report
        private int batchUILogUpdate(MessageLog msgObj)
        {
            //Updating txtbxAll.
            txtbxAll.AppendText("FAST system starting reconcile files now .....\n\n");
            txtbxAll.AppendText(msgObj.getAllMsg());
            txtbxAll.AppendText("\nFAST system ended reconcile files operations successfully.\n\n");
            txtbxAll.AppendText("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n");

            txtbxAll.Select(txtbxAll.TextLength - 1, 0);
            txtbxAll.ScrollToCaret();

            //Updating other richtextbox
            if (msgObj.getMsgCount("CHANGE") > 0)
            {
                txtbxChange.AppendText("Changes performed during synchronization: \n\n");
                txtbxChange.AppendText(msgObj.getChangesMsg());
                txtbxChange.AppendText("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");

                txtbxChange.Select(txtbxChange.TextLength - 1, 0);
                txtbxChange.ScrollToCaret();

                tbChanges.Text = "Changes(" + msgObj.getMsgCount("CHANGE") + ")";
            }
            else
            {
                //Set back to default.
                tbChanges.Text = "Changes";
            }

            if (msgObj.getMsgCount("CONFLICT") > 0)
            {
                txtbxConflict.AppendText("Conflicts founded during synchronization: \n\n");
                txtbxConflict.AppendText(msgObj.getConflictMsg());
                txtbxConflict.AppendText("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");

                txtbxConflict.Select(txtbxConflict.TextLength - 1, 0);
                txtbxConflict.ScrollToCaret();

                tbConflicts.Text = "Conflicts(" + msgObj.getMsgCount("CONFLICT") + ")";
            }
            else
            {
                tbConflicts.Text = "Conflicts";
            }

            if (msgObj.getMsgCount("ERROR") > 0)
            {
                txtbxError.AppendText("Exception encountered during synchronization: \n\n");
                txtbxError.AppendText(msgObj.getErrorMsg());
                txtbxError.AppendText("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");

                txtbxError.Select(txtbxError.TextLength - 1, 0);
                txtbxError.ScrollToCaret();

                tbError.Text = "Error(" + msgObj.getMsgCount("ERROR") + ")";
            }
            else
            {
                tbError.Text = "Error";
            }

            return msgObj.getMsgCount("ERROR");

        }

        //Clear log report button event
        private void ClearAll_Click_1(object sender, EventArgs e)
        {
            clearAll_log();
        }

        private void clearAll_log()
        {
            txtbxAll.Clear();
            txtbxChange.Clear();
            txtbxConflict.Clear();
            txtbxError.Clear();

            tbAll.Text = "All";
            tbChanges.Text = "Changes";
            tbConflicts.Text = "Conflicts";
            tbError.Text = "Error";
        }

        /***************************************** ListView Right Click Methods *********************************/

        private void fileViewLeft_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right &&
                fileViewLeft.SelectedItems.Count == 1 &&
                fileViewLeft.SelectedItems[0].ImageIndex == 0 /*only file can right click*/)
            {
                int index = int.Parse(fileViewLeft.SelectedItems[0].Name);
                fileDetailsLeftMenu.Items[fileDetailsLeftMenu.Items.Count - 1].Text = "" + index;
                fileDetailsLeftMenu.Show(MousePosition);
            }
            else if (e.Button == MouseButtons.Right &&
                fileViewLeft.SelectedItems.Count == 1 &&
                fileViewLeft.SelectedItems[0].ImageIndex == 1 /*Folder can right click*/)
            {
                int index = int.Parse(fileViewLeft.SelectedItems[0].Name);
                folderDetailsLeftMenu.Items[folderDetailsLeftMenu.Items.Count - 1].Text = "" + index;
                folderDetailsLeftMenu.Show(MousePosition);
            }
        }

        private void fileViewRight_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right &&
                fileViewRight.SelectedItems.Count == 1 &&
                fileViewRight.SelectedItems[0].ImageIndex == 0 /*only file can right click*/)
            {
                int index = int.Parse(fileViewRight.SelectedItems[0].Name);
                fileDetailsRightMenu.Items[fileDetailsRightMenu.Items.Count - 1].Text = "" + index;
                fileDetailsRightMenu.Show(MousePosition);
            }
            else if (e.Button == MouseButtons.Right &&
                fileViewRight.SelectedItems.Count == 1 &&
                fileViewRight.SelectedItems[0].ImageIndex == 1 /*Folder can right click*/)
            {
                int index = int.Parse(fileViewRight.SelectedItems[0].Name);
                folderDetailsRightMenu.Items[folderDetailsRightMenu.Items.Count - 1].Text = "" + index;
                folderDetailsRightMenu.Show(MousePosition);
            }
        }
        
        
        private void fileDetailsLeftMenu_ItemClicked(object sender, EventArgs e)
        {
            Process myProc = new Process();
            myProc.StartInfo.CreateNoWindow = true;
            try
            {
                int index = int.Parse(fileDetailsLeftMenu.Items[fileDetailsLeftMenu.Items.Count - 1].Text);
                String type = "";

                for (int i = 0; i < EditWith.DropDown.Items.Count; i++)
                {
                    type = EditWith.DropDown.Items[i].GetType().ToString();
                    if (type.Equals("System.Windows.Forms.ToolStripMenuItem"))
                        EditWith.DropDown.Items[i].Click += this.EditWith_SubItemClicked;
                }

                if (fileDetailsLeftMenu.Items[0].Selected)//edit can only run with notepad now
                {
                    string path = ((FileHandler)leftTreeDetails[index]).getFullFilePath();
                    FileInfo fi = new FileInfo(path);
                 
                    Process.Start(path);
                }
                else if (fileDetailsLeftMenu.Items[1].Selected)
                {
                    if (EditWith.DropDown.Items[0].Selected)
                    {
                        string path = ((FileHandler)leftTreeDetails[index]).getFullFilePath();
                        FileInfo fi = new FileInfo(path);
                        Process.Start("notepad.exe", path);
                    }

                }
                else if (fileDetailsLeftMenu.Items[2].Selected)
                {
                    string path = ((FileHandler)leftTreeDetails[index]).getFullFilePath();
                    FileInfo fi = new FileInfo(path);
                    String selectFileExplorer = @"/select, " + fi.FullName;
                    myProc.StartInfo.FileName = "Explorer";
                    myProc.StartInfo.Arguments = selectFileExplorer;
                    myProc.Start();
                }
                else if (fileDetailsLeftMenu.Items[3].Selected)//versioning selected
                {
                    //trigger versioning window
                    FileHandler fh = (FileHandler)leftTreeDetails[index];
                    int idx = fh.getVersioningIdx();
                    if (idx != -1)
                    {
                        List<FileHandler> fvl = ctrl.getVersionList(idx);
                        VersioningUI vu = new VersioningUI(this, fh, fvl);
                        vu.Show();
                    }
                    else
                    {
                        MessageBox.Show("There are no versions","FAST",MessageBoxButtons.OK,MessageBoxIcon.Information);
                    }
                }
                else if (fileDetailsLeftMenu.Items[4].Selected)
                {
                    string path = ((FileHandler)leftTreeDetails[index]).getFullFilePath();
                    FileInfo fi = new FileInfo(path);
                    string info = "Name: " + fi.Name + "\nLocation: " + fi.DirectoryName + "\nSize: " + fi.Length + " bytes" + "\n Created: " + fi.CreationTime + "\nModified: " + fi.LastWriteTime + "\nAccessed: " + fi.LastAccessTime;

                    fileDetailsLeftMenu.Close();
                }
                else if (fileDetailsLeftMenu.Items[5].Selected)
                {
                    string path = ((FileHandler)leftTreeDetails[index]).getFullFilePath();
                    FileInfo fi = new FileInfo(path);

                    string command = "/C " + "del " + '"' + fi.FullName + '"';
                    ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", command);
                    myProc.StartInfo = psi;
                    myProc.Start();
                    myProc.WaitForExit(); 
                    this.folderCompare_Click(sender, e);
                                    
                }
                else if (fileDetailsLeftMenu.Items[6].Selected)
                {
                    string path1 = ((FileHandler)leftTreeDetails[index]).getFullFilePath();

                    string path2 = ((FileHandler)rightTreeDetails[index]).getFullFilePath();
                    FileInfo fi1 = new FileInfo(path1);

                    String left = '"' + fi1.FullName + '"';
                    FileInfo fi2 = null;
                    String right = "";
                    if (!path2.Equals(null))
                    {
                        fi2 = new FileInfo(path2);
                        right = '"' + fi2.FullName + '"';
                    }
                    //This is for open winmerge
                    myProc.StartInfo.FileName = "WinMergeU";
                    myProc.StartInfo.Arguments = left + ' ' + right;
                    myProc.Start();

                }
            }
            catch (Exception e2)
            {
                Console.WriteLine("" + e2);
            }
        }

        private void fileDetailsRightMenu_ItemClicked(object sender, EventArgs e)
        {
            Process myProc = new Process();
            myProc.StartInfo.CreateNoWindow = true;
            try
            {
                int index = int.Parse(fileDetailsRightMenu.Items[fileDetailsRightMenu.Items.Count - 1].Text);
                if (fileDetailsRightMenu.Items[0].Selected)//edit can only run with notepad now
                {
                    string path = ((FileHandler)rightTreeDetails[index]).getFullFilePath();
                    FileInfo fi = new FileInfo(path);

                    Process.Start(path);
                }
                else if (fileDetailsRightMenu.Items[2].Selected)
                {
                    string path = ((FileHandler)rightTreeDetails[index]).getFullFilePath();
                    FileInfo fi = new FileInfo(path);
                    path = fi.DirectoryName;
                    String selectFileExplorer = @"/select, " + fi.FullName;
                    myProc.StartInfo.FileName = "Explorer";
                    myProc.StartInfo.Arguments = selectFileExplorer;
                    myProc.Start();
                }
                else if (fileDetailsRightMenu.Items[3].Selected)//versioning selected
                {
                    FileHandler fh = (FileHandler)rightTreeDetails[index];
                    int idx = fh.getVersioningIdx();
                    if (idx != -1)
                    {
                        List<FileHandler> fvl = ctrl.getVersionList(idx);
                 
                        VersioningUI vu = new VersioningUI(this, fh, fvl);
                        vu.Show();
                    }
                    else
                    {
                        MessageBox.Show("There are no versions", "FAST", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
                else if (fileDetailsRightMenu.Items[4].Selected)
                {
                    string path = ((FileHandler)rightTreeDetails[index]).getFullFilePath();
                    FileInfo fi = new FileInfo(path);
                    string info = "Name: " + fi.Name + "\nLocation: " + fi.DirectoryName + "\nSize: " + fi.Length + " bytes" + "\n Created: " + fi.CreationTime + "\nModified: " + fi.LastWriteTime + "\nAccessed: " + fi.LastAccessTime;

                    fileDetailsRightMenu.Close();
                    //MessageBox.Show(info, fi.Name + " file information");
                }
                else if (fileDetailsRightMenu.Items[5].Selected)
                {
                    string path = ((FileHandler)rightTreeDetails[index]).getFullFilePath();
                    FileInfo fi = new FileInfo(path);

                    string command = "/C " + "del " + '"' + fi.FullName + '"';
                    ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", command);
                    myProc.StartInfo = psi;
                    myProc.Start();
                    myProc.WaitForExit();
                    this.folderCompare_Click(sender, e);     
                }
            }
            catch (Exception e2)
            {
                Console.WriteLine("" + e2);
            }

        }
        
        private void folderDetailsLeftMenu_ItemClicked(object sender, EventArgs e)
        {
            Process myProc = new Process();
            try
            {

                int index = int.Parse(folderDetailsLeftMenu.Items[folderDetailsLeftMenu.Items.Count - 1].Text);
                if (folderDetailsLeftMenu.Items[0].Selected)//OPEN FOLDER
                {
                    string path = ((FolderHandler)leftTreeDetails[index]).getFullFolderPath();
                    string selectFileExplorer = @"/select, " + path;
                    myProc.StartInfo.FileName = "Explorer";
                    myProc.StartInfo.Arguments = selectFileExplorer;
                    myProc.Start();
                }
                else if (folderDetailsLeftMenu.Items[1].Selected)//Add new file
                {

                }
                else if (folderDetailsLeftMenu.Items[2].Selected)//Delete Folder
                {
                    switch (MessageBox.Show("Do you wish to delete the folder and everything inside?",
                               "Deletion Warning",
                              MessageBoxButtons.YesNo,
                              MessageBoxIcon.Exclamation))
                    {
                        case DialogResult.Yes:
                            string path = '"' + ((FolderHandler)leftTreeDetails[index]).getFullFolderPath() + '"';
                            string command = "/C" + "rmdir " + path + " /s /q ";
                            ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", command);
                            myProc.StartInfo = psi;
                            myProc.Start();
                            myProc.WaitForExit();
                            this.folderCompare_Click(sender, e);

                            break;

                        case DialogResult.No:
                            break;
                    }
                }
            }
            catch (Exception e2)
            {
                Console.WriteLine("" + e2);
            }

        }

        private void folderDetailsRightMenu_ItemClicked(object sender, EventArgs e)
        {
            Process myProc = new Process();
            try
            {
                int index = int.Parse(folderDetailsRightMenu.Items[folderDetailsRightMenu.Items.Count - 1].Text);
                if (folderDetailsRightMenu.Items[0].Selected)//OPEN FOLDER
                {
                    string path = ((FolderHandler)rightTreeDetails[index]).getFullFolderPath();
                    String selectFileExplorer = @"/select, " + path;
                    myProc.StartInfo.FileName = "Explorer";
                    myProc.StartInfo.Arguments = selectFileExplorer;
                    myProc.Start();
                }
                else if (folderDetailsRightMenu.Items[1].Selected)//Add new file
                {

                }
                else if (folderDetailsRightMenu.Items[2].Selected)
                {
                    switch (MessageBox.Show("Do you wish to delete the folder and everything inside?",
                                            "Deletion Warning",
                                             MessageBoxButtons.YesNo,
                                             MessageBoxIcon.Exclamation))
                    {
                        case DialogResult.Yes:
                            string path = '"' + ((FolderHandler)rightTreeDetails[index]).getFullFolderPath() + '"';
                            string command = "/C" + "rmdir " + path + " /s /q ";
                            ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", command);
                            myProc.StartInfo = psi;
                            myProc.Start();
                            myProc.WaitForExit();
                            this.folderCompare_Click(sender, e);
                            break;

                        case DialogResult.No:
                            break;
                    }
                }
            }
            catch (Exception e2)
            {
                Console.WriteLine("" + e2);
            }

        }
        

        private void fileViewLeft_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isBalanceView && fileViewLeft.SelectedItems.Count > 0)
            {
                fileViewLeft.Items[indexSelected].BackColor = Color.White;
                fileViewRight.Items[indexSelected].BackColor = Color.White;

                indexSelected = fileViewLeft.SelectedItems[0].Index;
                fileViewRight.Items[indexSelected].BackColor = Color.Beige;
                fileViewRight.Items[indexSelected].EnsureVisible();
            }
        }

        private void fileViewRight_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isBalanceView && fileViewRight.SelectedItems.Count > 0)
            {
                fileViewLeft.Items[indexSelected].BackColor = Color.White;
                fileViewRight.Items[indexSelected].BackColor = Color.White;

                indexSelected = fileViewRight.SelectedItems[0].Index;
                fileViewLeft.Items[indexSelected].BackColor = Color.Beige;
                fileViewLeft.Items[indexSelected].EnsureVisible();
            }
        }


        private void EditWith_SubItemClicked(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;
            Console.WriteLine("{0} clicked", item.Text);
        }

        /***************************************** End ListView Right Click Methods *********************************/

        //UI exception handling Method
        private void verifyLocation(string lRoot, String rRoot)
        {

            if ((String.IsNullOrEmpty(lRoot)) && (String.IsNullOrEmpty(rRoot)))
            {
                throw new CustomException("You have not selected two valid folders path!Please try again.");
            }
              
            if (String.IsNullOrEmpty(lRoot))
            {
                throw new CustomException("You have not selected valid left folder path!Please try again.");
            }
            else if (String.IsNullOrEmpty(rRoot))
            {
                throw new CustomException("You have not selected valid right folder path!Please try again.");
            }
            else if (!Directory.Exists(lRoot))
            {
                txtLFolder.Text = "";
                throw new CustomException("You have selected a non existent left folder path!Please try again.");
            }
            else if (!Directory.Exists(rRoot))
            {
                txtRFolder.Text = "";
                throw new CustomException("You have selected a non existent right folder path!Please try again.");
            }

            if (String.Equals(lRoot, rRoot))
            {
                txtLFolder.Text = "";
                txtRFolder.Text = "";
                throw new CustomException("You have selected two same folders path!Please try again.");
            }
        }

        //Method for versionUI to set comments
        public void setVersionComments(List<FileHandler> vList, int vIdx)
        {
            ctrl.setVersionList(vList, vIdx);
        }
       
    }
}
